
// 封装倒计时函数
function countdown() {
  // 设置考试时长（单位：秒）
  const examTime = 30
  let remaining = examTime

  function updateCountdown() {
    let m = parseInt(remaining / 60 % 60)
    m = m < 10 ? '0' + m : m
    let s = parseInt(remaining % 60)
    s = s < 10 ? '0' + s : s

    // 倒计时盒子
    document.querySelector('.time span').innerHTML = `${m}'${s}''`
  }
  updateCountdown()

  // 倒计时结束交卷
  function submitExam() {
    clearInterval(countDownInterval)
    document.querySelector('.time span').innerHTML = `00'00''`

    // 成绩计算
    score = 0
    // 使用reduce方法计算本次成绩
    score = questionList.reduce((sum, item, i) => {
      const answer = localStorage.getItem(`answered_${i}`)
      // console.log(index, answer)
      if (answer === item.correctAnswer) sum += 2
      // console.log(item.correctAnswer)
      return sum
    }, score)
    // 存储历史成绩
    user[index].historicalScore.push(score)
    localStorage.setItem('exam-data', JSON.stringify(user))
    // 临时成绩存储
    localStorage.setItem('score', score)

    // 交卷跳转
    alert('考试结束')
    location.href = './look.html'
  }

  // 开启定时器
  let countDownInterval = setInterval(() => {
    if (remaining <= 0) {
      submitExam()
    } else {
      remaining--
      updateCountdown()
    }
  }, 1000)
}

countdown()






//得到用户信息 及 登录时存储的令牌
const user = JSON.parse(localStorage.getItem('exam-data'))
const token = localStorage.getItem('token')
// console.log(user, token)
// 查找与token匹配的用户
function findUserByToken(user, token) {
  const index = user.findIndex(user => user.account === token)
  const matchedUser = user[index]
  return { matchedUser, index }
}
// 调用功能查找用户
// index为用户在user数组中的索引,用于历史成绩的添加
const { matchedUser, index } = findUserByToken(user, token)
const { id, name, account } = matchedUser
// console.log("找到的用户信息：", { id, name, account })
// console.log(index)

// 修改页面信息
document.querySelector('.font_dl p:nth-child(1)').innerHTML = `姓名：${name}`
document.querySelector('.font_dl p:nth-child(2)').innerHTML = `学号：${account}`

const amount = questionList.length
const totalScore = questionList.length * 2
document.querySelector('.font_info p:nth-child(1)').innerHTML = `题量：${amount}.0`
document.querySelector('.font_info p:nth-child(2)').innerHTML = `满分：${totalScore}.0`
document.querySelector('.choice h2').innerHTML = `一、单选题（共${amount}题，${totalScore}.0分）`
document.querySelector('.choiceNum').innerHTML = `一、单选题（${totalScore}.0）分`

// 外部js导入试卷渲染函数
testPaper(questionList)
